package nmcli

import (
	"fmt"
	"os/exec"
	"strings"
)

const (
	UP     = "up"
	DOWN   = "down"
	ADD    = "+"
	DELETE = "-"
	YES    = "yes"
	No     = "no"
)

// nmcli connection up "有线连接 1"
func UpDownConnect(connectionID string, updown string) ([]string, error) {
	if err := checkHasNmcli(); err != nil {
		return nil, err
	}

	execCmd := []string{
		"connection",
		updown,
		connectionID,
	}

	var cmdFields []string
	for key, cmd := range execCmd {
		if key == 2 {
			cmdFields = append(cmdFields, cmd)
		} else {
			cmdFields = append(cmdFields, strings.Fields(cmd)...)
		}

	}
	//loglog.Handler.Info("running nmcli %v", cmdFields)
	cmd := exec.Command("nmcli", cmdFields...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		//loglog.Handler.Warn("cmd out pipe produced err")
		return nil, err
	}

	stderr, err := cmd.StderrPipe()
	if err != nil {
		//loglog.Handler.Warn("cmd out err produced")
		return nil, err
	}

	err = cmd.Start()
	if err != nil {
		//loglog.Handler.Warn("cmd failed to start")
		return nil, err
	}

	data := GetStdoutText(stdout)
	if errOut := GetStdoutText(stderr); errOut != nil {
		return nil, fmt.Errorf(strings.Join(errOut, " "))
	}

	cmd.Wait()
	return data, err

}

// 是否忽略网关
// nmcli connection modify Wired\ connection\ 2 ipv4.never-default yes
func UnusedRoute(connectionID string, ret string) ([]string, error) {
	if err := checkHasNmcli(); err != nil {
		return nil, err
	}

	execCmd := []string{
		"connection",
		"modify",
		connectionID,
		"ipv4.never-default",
		ret,
	}

	var cmdFields []string
	for key, cmd := range execCmd {
		if key == 2 {
			cmdFields = append(cmdFields, cmd)
		} else {
			cmdFields = append(cmdFields, strings.Fields(cmd)...)
		}

	}
	//loglog.Handler.Info("running nmcli %v", cmdFields)
	cmd := exec.Command("nmcli", cmdFields...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		//loglog.Handler.Warn("cmd out pipe produced err")
		return nil, err
	}

	stderr, err := cmd.StderrPipe()
	if err != nil {
		//loglog.Handler.Warn("cmd out err produced")
		return nil, err
	}

	err = cmd.Start()
	if err != nil {
		//loglog.Handler.Warn("cmd failed to start")
		return nil, err
	}

	data := GetStdoutText(stdout)
	if errOut := GetStdoutText(stderr); errOut != nil {
		return nil, fmt.Errorf(strings.Join(errOut, " "))
	}

	cmd.Wait()
	return data, err

}
